{% extends "base.html" %}

{% block title %}{{ chapter.title }} - {{ novel.title }} - 畅读小说网{% endblock %}

{% block content %}
<div class="reading-container">
    <div class="reading-header">
        <div class="novel-title">{{ novel.title }}</div>
        <div class="chapter-title">{{ chapter.title }}</div>
        <div class="reading-controls">
            <div class="font-size-control">
                <button id="font-decrease" class="btn-font">-</button>
                <button id="font-increase" class="btn-font">+</button>
            </div>
            <div class="theme-control">
                <button id="theme-day" class="btn-theme active">日间</button>
                <button id="theme-night" class="btn-theme">夜间</button>
            </div>
            {% if user.is_authenticated %}
                {% if is_in_bookshelf %}
                    <a href="javascript:void(0);" id="btn-remove-bookshelf" class="btn-bookshelf btn-in-bookshelf">已在书架</a>
                {% else %}
                    <a href="javascript:void(0);" id="btn-add-bookshelf" class="btn-bookshelf btn-add-bookshelf">加入书架</a>
                {% endif %}
            {% endif %}
            <a href="{% url 'novel_detail' novel.id %}" class="btn-back">返回目录</a>
        </div>
    </div>

    <div class="reading-content">
        <div class="chapter-content">
            {{ chapter.content|linebreaks }}
        </div>
    </div>

    <div class="reading-footer">
        <div class="chapter-navigation">
            {% if prev_chapter %}
                <a href="{% url 'read_chapter' novel.id prev_chapter.id %}" class="btn-prev">上一章</a>
            {% else %}
                <span class="btn-prev disabled">上一章</span>
            {% endif %}

            <a href="{% url 'novel_detail' novel.id %}" class="btn-directory">目录</a>

            {% if next_chapter %}
                <a href="{% url 'read_chapter' novel.id next_chapter.id %}" class="btn-next">下一章</a>
            {% else %}
                <span class="btn-next disabled">下一章</span>
            {% endif %}
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 字体大小调整
        const fontDecreaseBtn = document.getElementById('font-decrease');
        const fontIncreaseBtn = document.getElementById('font-increase');
        const chapterContent = document.querySelector('.chapter-content');

        let fontSize = localStorage.getItem('reading_font_size') || 18;
        chapterContent.style.fontSize = fontSize + 'px';

        fontDecreaseBtn.addEventListener('click', function() {
            if (fontSize > 14) {
                fontSize -= 2;
                chapterContent.style.fontSize = fontSize + 'px';
                localStorage.setItem('reading_font_size', fontSize);
            }
        });

        fontIncreaseBtn.addEventListener('click', function() {
            if (fontSize < 28) {
                fontSize += 2;
                chapterContent.style.fontSize = fontSize + 'px';
                localStorage.setItem('reading_font_size', fontSize);
            }
        });

        // 主题切换
        const themeDayBtn = document.getElementById('theme-day');
        const themeNightBtn = document.getElementById('theme-night');
        const readingContainer = document.querySelector('.reading-container');

        let currentTheme = localStorage.getItem('reading_theme') || 'day';

        if (currentTheme === 'night') {
            readingContainer.classList.add('night-mode');
            themeDayBtn.classList.remove('active');
            themeNightBtn.classList.add('active');
        }

        themeDayBtn.addEventListener('click', function() {
            readingContainer.classList.remove('night-mode');
            themeDayBtn.classList.add('active');
            themeNightBtn.classList.remove('active');
            localStorage.setItem('reading_theme', 'day');
        });

        themeNightBtn.addEventListener('click', function() {
            readingContainer.classList.add('night-mode');
            themeDayBtn.classList.remove('active');
            themeNightBtn.classList.add('active');
            localStorage.setItem('reading_theme', 'night');
        });

        // 加入/移出书架
        const addBookshelfBtn = document.getElementById('btn-add-bookshelf');
        const removeBookshelfBtn = document.getElementById('btn-remove-bookshelf');

        if (addBookshelfBtn) {
            addBookshelfBtn.addEventListener('click', function() {
                addToBookshelf();
            });
        }

        if (removeBookshelfBtn) {
            removeBookshelfBtn.addEventListener('click', function() {
                removeFromBookshelf();
            });
        }

        function addToBookshelf() {
            fetch('/api/bookshelf/add_to_bookshelf/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    novel_id: {{ novel.id }}
                })
            })
           .then(response => response.json())
           .then(data => {
                if (data.detail) {
                    // 更新阅读记录
                    updateReadingProgress();

                    // 更改按钮状态
                    if (addBookshelfBtn) {
                        addBookshelfBtn.style.display = 'none';
                    }
                    if (removeBookshelfBtn) {
                        removeBookshelfBtn.style.display = 'inline-block';
                    }
                }
            })
           .catch(error => {
                console.error('Error:', error);
            });
        }

        function removeFromBookshelf() {
            fetch('/api/bookshelf/remove_from_bookshelf/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    novel_id: {{ novel.id }}
                })
            })
           .then(response => response.json())
           .then(data => {
                if (data.detail) {
                    // 更改按钮状态
                    if (removeBookshelfBtn) {
                        removeBookshelfBtn.style.display = 'none';
                    }
                    if (addBookshelfBtn) {
                        addBookshelfBtn.style.display = 'inline-block';
                    }
                }
            })
           .catch(error => {
                console.error('Error:', error);
            });
        }

        // 更新阅读进度
        function updateReadingProgress() {
            fetch('/api/chapters/{{ chapter.id }}/read/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
           .then(response => response.json())
           .catch(error => {
                console.error('Error:', error);
            });
        }

        // 自动更新阅读进度
        {% if user.is_authenticated %}
        updateReadingProgress();
        {% endif %}

        // 键盘导航
        document.addEventListener('keydown', function(e) {
            // 左箭头：上一章
            if (e.key === 'ArrowLeft') {
                {% if prev_chapter %}
                window.location.href = "{% url 'read_chapter' novel.id prev_chapter.id %}";
                {% endif %}
            }
            // 右箭头：下一章
            else if (e.key === 'ArrowRight') {
                {% if next_chapter %}
                window.location.href = "{% url 'read_chapter' novel.id next_chapter.id %}";
                {% endif %}
            }
        });

        // 获取CSRF Token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie!== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    });
</script>

<style>
    /* 全局样式重置 */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Arial', sans-serif;
        line-height: 1.6;
    }

    /* 阅读容器样式 */
   .reading-container {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px 30px;
        background-color: #f9f9f9;
        min-height: 100vh;
        transition: background-color 0.3s ease, color 0.3s ease;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    }

   .reading-container.night-mode {
        background-color: #1a1a1a;
        color: #ccc;
    }

    /* 阅读头部样式 */
   .reading-header {
        text-align: center;
        margin-bottom: 30px;
        padding-bottom: 20px;
        border-bottom: 1px solid #eee;
        position: relative;
    }

   .night-mode.reading-header {
        border-bottom-color: #333;
    }

   .reading-header::after {
        content: "";
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        width: 50px;
        height: 2px;
        background-color: #007bff;
        margin-top: 10px;
    }

   .night-mode.reading-header::after {
        background-color: #0056b3;
    }

   .novel-title {
        font-size: 16px;
        color: #666;
        margin-bottom: 10px;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

   .night-mode.novel-title {
        color: #999;
    }

   .chapter-title {
        font-size: 28px;
        font-weight: 600;
        margin-bottom: 20px;
        line-height: 1.2;
    }

    /* 阅读控制按钮样式 */
   .reading-controls {
        display: flex;
        justify-content: center;
        gap: 10px;
        flex-wrap: wrap;
    }

   .btn-font,
   .btn-theme,
   .btn-bookshelf,
   .btn-back {
        padding: 8px 15px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease, color 0.3s ease;
        font-size: 14px;
        text-decoration: none; /* 消除链接下划线 */
    }

   .btn-font {
        font-size: 18px;
        font-weight: bold;
        background-color: #f4f4f4;
        color: #333;
    }

   .night-mode.btn-font {
        background-color: #2a2a2a;
        color: #ccc;
    }

   .btn-theme {
        text-transform: uppercase;
        letter-spacing: 1px;
    }

   .btn-theme.active {
        background-color: #007bff;
        color: white;
    }

   .night-mode.btn-theme.active {
        background-color: #0056b3;
    }

   .btn-bookshelf {
        background-color: #f4f4f4;
        color: #333;
    }

   .night-mode.btn-bookshelf {
        background-color: #2a2a2a;
        color: #ccc;
    }

   .btn-bookshelf.btn-in-bookshelf {
        background-color: #f4e8c1; /* 牛皮纸颜色 */
        color: #333;
    }

   .night-mode.btn-bookshelf.btn-in-bookshelf {
        background-color: #d6c7a5; /* 夜间模式下的牛皮纸颜色 */
        color: #ccc;
    }

   .btn-back {
        background-color: #f4f4f4;
        color: #333;
    }

   .night-mode.btn-back {
        background-color: #2a2a2a;
        color: #ccc;
    }

    /* 阅读内容样式 */
   .reading-content {
        line-height: 1.8;
        margin-bottom: 30px;
        padding-bottom: 30px;
        border-bottom: 1px solid #eee;
    }

   .night-mode.reading-content {
        border-bottom-color: #333;
    }

   .chapter-content {
        font-size: 18px;
        text-indent: 2em;
    }

   .night-mode.chapter-content {
        color: #bbb;
    }

    /* 阅读底部样式 */
   .reading-footer {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-wrap: wrap;
        margin-top: 20px;
    }

   .chapter-navigation {
        display: flex;
        gap: 10px;
    }

   .btn-prev,
   .btn-next,
   .btn-directory {
        padding: 8px 15px;
        border: none;
        border-radius: 5px;
        background-color: #f4f4f4;
        color: #333;
        text-decoration: none; /* 消除链接下划线 */
        transition: background-color 0.3s ease, color 0.3s ease;
    }

   .night-mode.btn-prev,
   .night-mode.btn-next,
   .night-mode.btn-directory {
        background-color: #2a2a2a;
        color: #ccc;
    }

   .btn-prev.disabled,
   .btn-next.disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
       .reading-container {
            padding: 15px;
        }

       .chapter-title {
            font-size: 24px;
        }

       .reading-controls {
            justify-content: space-between;
        }

       .chapter-navigation {
            width: 100%;
            justify-content: space-between;
            margin-bottom: 15px;
        }

       .reading-footer {
            flex-direction: column;
            gap: 15px;
        }
    }
</style>
{% endblock %}